package cn.laowen.org.service.impl;

import cn.laowen.basic.service.impl.BasicServiceImpl;
import cn.laowen.basic.util.MD5Utils;
import cn.laowen.basic.util.PageList;
import cn.laowen.basic.util.StrUtils;
import cn.laowen.org.domain.Employee;
import cn.laowen.org.mapper.EmployeeMapper;
import cn.laowen.org.query.EmployeeQuery;
import cn.laowen.org.service.IEmployeeService;
import cn.laowen.user.domain.Logininfo;
import cn.laowen.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BasicServiceImpl<Employee> implements IEmployeeService {
    //1.一般业务实现可以通公共业务实现层来实现

    //2.特殊的业务实现需要自己重写

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;


    /*
     * employee CRU 级联保存logininfo
     */


    @Override
    public void save(Employee employee) {
        initEmployee(employee);//初始化employee的salt和密码
        //级联保存logininfo
        Logininfo logininfo = employee2logininfo(employee);
        logininfoMapper.save(logininfo);//保存到 t_logininfo
        employee.setLogininfo_id(logininfo.getId());//给 employee设置logininfo_id
        employeeMapper.save(employee);//保存到 t_employee
    }

    /**
     * employee对象转logininfo对象
     * @return
     */
    private Logininfo employee2logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);//使用工具类同名原则拷贝,把user中logininfo有的属性copy过去
        logininfo.setType(0);//设置Type为 0：员工
        return logininfo;
    }

    /**
     * 初始化employee的salt盐值和密码
     * @param employee
     */
    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);//生成一个32位的盐值
        employee.setSalt(salt);//设置盐值
        String md5Password = MD5Utils.encrypByMd5(employee.getPassword() + salt);//使用盐值加密密码
        employee.setPassword(md5Password);//设置密码为加密后的密码
    }
}
